import { Injectable } from '@angular/core';
import { format, subHours, subDays, startOfDay, startOfHour } from 'date-fns';

@Injectable({
    providedIn: 'root'
})
export class TimeRangeService {

    constructor() { }

    getTimeRange() {
        // 当前时间对小时取整
        const hourCurrent = this.getCurrentHour();

        const timeRange = {
            'today': {
                startTime: startOfDay(new Date()),
                endTime: new Date()
            },
            'last_24_hours': {
                startTime: subHours(startOfHour(hourCurrent), 24),
                endTime: new Date()
            },
            'last_7_days': {
                startTime: subDays(startOfDay(new Date()), 7),
                endTime: new Date()
            },
            'last_30_days': {
                startTime: subDays(startOfDay(new Date()), 30),
                endTime: new Date()
            },
            'last_1_hour': {
                startTime: subHours(new Date(), 1),
                endTime: new Date()
            }
        };
        return timeRange;
    }

    // 当前时间对小时取整,如： 2019-04-08 16:23:46 ===> 2019-04-08 16:00
    getCurrentHour() {
        const hourCurrent = new Date(format(new Date(), 'YYYY-MM-DD HH:00'));
        return hourCurrent;
    }
}
